package cn.wgx.module.question.service;

import cn.wgx.commons.storage.filetool.FileUploadTool;
import cn.wgx.commons.util.ExcelReader;
import cn.wgx.commons.util.IdGen;
import cn.wgx.commons.util.StringUtils;
import cn.wgx.module.base.services.BaseService;
import cn.wgx.module.question.entity.QQuestionExample;
import cn.wgx.module.question.entity.mapper.QQuestionMapper;
import cn.wgx.module.question.entity.QQuestion;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class QQuestionService extends BaseService<QQuestion> {

    @Resource
    QQuestionMapper mapper;

    @Transactional(readOnly = true)
    public List<QQuestion> getList(QQuestion record, Boolean desc) {
		QQuestionExample example = new QQuestionExample();
		if(record != null){
            QQuestionExample.Criteria criteria = example.createCriteria();
            if(StringUtils.isNotBlank(record.getContent())){
                criteria.andContentLike("%" + record.getContent() + "%");
            }
            if(StringUtils.isNotBlank(record.getTitle())){
                criteria.andTitleLike("%" + record.getTitle() + "%");
            }
            if(StringUtils.isNotBlank(record.getAnswer())){
                criteria.andAnswerLike("%" + record.getAnswer() + "%");
            }
        }
		example.setOrderByClause("createDate " + (desc?"desc": "asc"));
		return mapper.selectByExample(example);
    }

    @Transactional(readOnly = true)
    public QQuestion getOne(Integer id) {
		return mapper.selectByPrimaryKey(id);
    }

    @Transactional
    public QQuestion insertOne( QQuestion record) {
        filter(record, true);
        record.set_result(mapper.insertSelective(record));
        return record;
    }


    public Map<String, String> addByExcel(MultipartFile multipartFile) {
        Map<String, String> hashMap = Maps.newHashMap();
        int successNum = 0, failsNum = 0;
        StringBuffer sb = new StringBuffer();
        sb.append("失败的行数: ");
        String fileName = IdGen.uuid() + ".xlsx";
        String filePath = System.getProperty("java.io.tmpdir");
        File file = new File(filePath + File.separator + fileName);
        try {
            multipartFile.transferTo(file);
            if (file.exists()) {
                List<List<List<String>>> sheetList = ExcelReader.readExcel(file, 13);
                if (sheetList != null && !sheetList.isEmpty()) {
                    String hash = IdGen.uuid();
                    for (int i = 0, n = sheetList.size(); i < n; i++) {//循环sheet表
                        List<List<String>> rowList = sheetList.get(i);
                        for (int j = 1, m = rowList.size(); j < m; j++) {//循环每一行数据
                            List<String> colList = rowList.get(j);
                            if(colList != null && colList.size() > 0){
                                String s = colList.get(0);
                                if(StringUtils.isNotBlank(s) && s.length() < 4
                                        && (s.contains("单选") || s.contains("多选") || s.contains("判断"))){
                                    QQuestion qQuestion = new QQuestion();
                                    qQuestion.setType(s.contains("单选")?1: s.contains("多选")?2:3);
                                    qQuestion.setTitle(colList.get(1));
                                    qQuestion.setAnswer(colList.get(2));
                                    qQuestion.setRemark(colList.get(3));
                                    qQuestion.setLabel(colList.get(4));
                                    qQuestion.setScore(NumberUtils.isDigits(colList.get(5))? Integer.parseInt(colList.get(5)): 0);
                                    qQuestion.setHash(hash);
                                    StringBuilder sbb = new StringBuilder();
                                    for(int x = 6,y = colList.size(); x < y ;x ++){
                                        if(StringUtils.isNotBlank(colList.get(x))){
                                            if(sbb.length() != 0){
                                                sbb.append("|");
                                            }
                                            sbb.append(colList.get(x));
                                        }
                                    }
                                    qQuestion.setContent(sbb.toString());
                                    insertOne(qQuestion);
                                    if(qQuestion.get_result() > 0){
                                        successNum ++;
                                    }else{
                                        failsNum ++;
                                        sb.append(j + " - " + s +",");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            log.error("导入EXCEL失败: {}" + e.getMessage());
        }finally {
            FileUploadTool.delFile(file);//删除临时文件
        }
        hashMap.put("successNum", successNum+"");
        hashMap.put("failsNum", failsNum+"");
        hashMap.put("eMsg", failsNum == 0 ? "" : sb.toString());
        return hashMap;
    }

    @Transactional
    public QQuestion updateOne( QQuestion record) {
        mapper.updateByPrimaryKeySelective(record);
        return record;

    }


    @Transactional
    public int deleteOne( Integer id) {
        return mapper.deleteByPrimaryKey(id);
    }

    public void filter(QQuestion record, boolean insert){
        if(insert){
            String content = record.getContent() == null?"":record.getContent();
            String title = record.getTitle() == null?"":record.getTitle();
            String answer = record.getAnswer() == null?"":record.getAnswer();
            record.setContent(content.replaceAll("\n", "</br>").replaceAll("\r","</br>"));
            record.setTitle(title.replaceAll("\n", "</br>").replaceAll("\r","</br>"));
            record.setAnswer(answer.replaceAll("\n", "</br>").replaceAll("\r","</br>"));
        }else{

        }
        super.filter(record,insert);
    }


    public int delete(List<Integer> ids) {
        QQuestionExample example = new QQuestionExample();
        example.createCriteria().andQuestion_idIn(ids);
        return mapper.deleteByExample(example);
    }
}